package cn.lkk.samples.lang.fundamental.Operators;

/**
 * Created by lkk on 2015/5/11.
 */
public class ConversionAndCast {

    public static void main(String[] args) {
        convert();
        operatorConvert();
        cast();
    }

    /**
     * 演示自动转换
     */
    public static void convert() {

        byte aByte = 1;
        short aShort = 1;
        int aInt = 1;
        long aLong = 1;
        float aFloat = 1.0f;
        double aDouble = 1.0;
        char aChar = 'a';

        //以下抓换都是允许的
        aShort = aByte;
        aInt = aByte;
        aLong = aInt;
        aDouble = aFloat;
        aDouble = aInt;
        aInt = aChar;

        //从多字节转少字节是不允许的
        //aByte = aShort;
    }

    /**
     * 演示在二元运算符中的自动转换
     */
    public static void operatorConvert() {

        long aLong = 1;
        float aFloat = 1.0f;
        double aDouble = 1.0;
        int anyType = 1;

        double doubleResult = aDouble + anyType;// 运算符中有double，则结果为double
        float floatResult = aFloat + anyType;//否则，运算符中有float，则结果为float
        long longResult = aLong + anyType; //否则，运算符中有long，则结果为long
        int intResult = anyType + anyType; //否则，结果为int

    }

    /**
     * 演示强制转换
     */
    public static void cast() {
        //如果从多字节转少字节，可能出现信息丢失，所以需要强制类型转换
        int a = 48;
        byte b = (byte) a; //b=48

        a = 300;
        b = (byte) a; //b=44，溢出会被截断
        System.out.println(b);
    }
}
